package com.jxd.petMgr.servlet;

import com.jxd.petMgr.model.PetOwner;
import com.jxd.petMgr.service.IAccountService;
import com.jxd.petMgr.service.IPetOwnerService;
import com.jxd.petMgr.service.impl.AccountServiceImpl;
import com.jxd.petMgr.service.impl.PetOwnerServiceImpl;
import com.jxd.petMgr.util.PageUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/accountListServlet")
public class AccountListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        IAccountService accountService = new AccountServiceImpl();
        IPetOwnerService petOwnerService = new PetOwnerServiceImpl();
        PageUtil pageUtil = new PageUtil();
//        //设置搜索信息
//        String priceMin = request.getParameter("price_min");
//        String priceMax = request.getParameter("price_max");
//        String typeName = request.getParameter("typeName");
//        Map<String,String> mapInfo = new HashMap<>();
//        mapInfo.put("priceMin",priceMin);
//        mapInfo.put("priceMax",priceMax);
//        mapInfo.put("typeName",typeName);
        //设置编码格式
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");
        //通过session取到的对象只有id是准确的，其他属性不一定准确
        HttpSession session = request.getSession();
        PetOwner master = (PetOwner) session.getAttribute("petOwner");
        int petOwnerId = master.getId();
        //如果开启分页会向servlet传两个参数page   limit
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        int count = accountService.getAccountByPetOwnerIDCount(petOwnerId);
        //设置分页工具
        pageUtil.setCount(count);
        pageUtil.setCurrentPage(page);
        pageUtil.setLimit(limit);

        List<Map<String,Object>> accountList = accountService.getAccountByPetOwnerId(pageUtil,petOwnerId);
        JSONArray jsonArray = JSONArray.fromObject(accountList);
        JSONObject jsonObject = new JSONObject();
        //封装数据
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",count);
        jsonObject.put("data",jsonArray);
        //使用输出流的方式向页面输出信息
        //不能使用请求转发或重定向，会无限循环
        PrintWriter pw = response.getWriter();
        //直接将对象以字符串形式输出页面
        pw.print(jsonObject.toString());
        pw.flush();
        pw.close();
    }
}
